﻿using Convertor.Interface;
using System;
using System.Linq;
using System.IO;
using System.Windows;
using Wpf.CommonTools.BooleanExtension;
using Wpf.CommonTools.NumberExtension;
using Wpf.CommonTools.SystemExtension;
using Wpf.CommonTools.DateTimeExtension;
using Wpf.CommonTools.StringExtension;
using System.Collections.ObjectModel;
using System.Windows.Shell;
using System.Reflection;

namespace Convertor
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup_1(object sender, StartupEventArgs e)
        {
            SplashScreen s = new SplashScreen("Images/logo.png");
            s.Show(false);

            //Use input parameter to open un template--------------------------------
            Config.Args = e.Args;
            Config.SafeModel = e.Args.Length > 0 && e.Args[0].Equals("-safe", StringComparison.OrdinalIgnoreCase);

            getStartConfigFromDisk(sender); //get work space path from config
            try
            {
                DirectoryInfo df = new DirectoryInfo(Config.GlobalConfig.WorkspacePath);
                if (!df.Exists)
                {
                    df.Create();
                }
            }
            catch { Config.GlobalConfig.WorkspacePath = new Config().WorkspacePath; }
            if (!Config.SafeModel)
            {
                getConfigFromDisk(sender); //get configs from work space
                //Loading all plugin from disk to gloable varaible----------------------------
                PluginHandler.LoadPlugs(); // First To load all plugin
                Convertor.Plugin.Language.Change(Config.GlobalConfig.Language); //change ui language
                PluginHandler.LoadPlugs(); //reload all plugin to apply ui language
                //Config.GlobalConfig.AllPlugins.PropertyChanged += AllPlugins_PropertyChanged;

                Config.CurrentTemplate.PropertyChanged += Template_PropertyChanged;

                foreach (var plugin in Config.GlobalConfig.AllPlugins)
                {
                    IPluginLanguages iLanguage = plugin.Value as IPluginLanguages;
                    if (iLanguage != null)
                    {
                        ResourceDictionary resourceDictionary = new ResourceDictionary();
                        foreach (string path in iLanguage.LanguagePaths)
                        {
                            resourceDictionary.Source = new Uri(path, UriKind.Relative);
                        }
                        Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
                        Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
                    }
                }

                //loading all template from disk--------------------------------------------
                try
                {
                    PluginHandler.LoadAllTemplates();
                }
                catch (Exception ex)
                {
                    Convertor.Code.Log.Write(sender, ex);
                }

                //Loading Template from last saved temp file----------------------------
                if (e.Args.Length > 0 && e.Args[0] == "NewTemplate")
                {
                    TemplateToSaveContainer temp = new TemplateToSaveContainer();

                    var count = Config.GlobalConfig.TemplateList.Count(m => m.Name == temp.Name);
                    while (count > 0)
                    {
                        temp = new TemplateToSaveContainer();
                        count = Config.GlobalConfig.TemplateList.Count(m => m.Name == temp.Name);
                    }
                    Config.CurrentTemplate.Container = temp;
                    Config.CurrentTemplate.Container.Path = Config.TempPluginsSavePath;
                }
                else
                {
                    try
                    {
                        Config.CurrentTemplate.Container = PluginHandler.LoaTemplateFromSerializeFile(Config.TempPluginsSavePath);
                        var a = Config.GlobalConfig.TemplateList.Where(k => k.Name == Config.CurrentTemplate.Container.Name).FirstOrDefault();
                        if (a != null)
                        {
                            Config.CurrentTemplate.Container.Path = a.Path;
                        }
                    }
                    catch (Exception ex)
                    {
                        Convertor.Code.Log.Write(sender, ex);
                    }
                }
                Config.CurrentPlugin.SelectedPlugins.CollectionChanged += Plugins_CollectionChanged;


                createJumpList();

            }
            s.Close(new TimeSpan(0, 0, 0));
        }

        private void Application_Exit_1(object sender, ExitEventArgs e)
        {
            saveStartConfigToDisk();
            saveConfigToDisk();
        }

        private void createJumpList()
        {
            //JumpList jumpList = new JumpList();
            //JumpList.SetJumpList(Application.Current, jumpList);
            //JumpTask helloTask = new JumpTask();
            //helloTask.Title = UILanguage.TryFindResource("MenuNew");
            //helloTask.Description = "";
            //helloTask.ApplicationPath = Assembly.GetEntryAssembly().Location;
            //helloTask.Arguments = "NewTemplate";
            //jumpList.JumpItems.Add(helloTask);
            //jumpList.ShowFrequentCategory = true;
            //jumpList.ShowRecentCategory = true;

            //jumpList.Apply();
        }
        private void Application_DispatcherUnhandledException_1(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
#if DEBUG
            string info = e.Exception.ToString();
            System.Windows.MessageBox.Show(info);
#else
            //var result = System.Windows.MessageBox.Show(
            //    UILanguage.FindResource("Windows_Message_ErrorReportContent"),
            //    UILanguage.FindResource("Windows_Message_ErrorReportTitle"),
            //    MessageBoxButton.YesNo);
            //if (result == MessageBoxResult.Yes)
            //{
            //    //SendMessage send = new SendMessage("Convertor");
            //    //send.StartSend(e.ToString(), (object sender1, EventArgs e1) =>
            //    //{
            //    //    SendMessage e2 = sender1 as SendMessage;
            //    //});
            //}
#endif
            try
            {
                PluginHandler.SavePluginAsTemplateToDisk(Config.CurrentPlugin, true);
            }
            catch { }
            Convertor.Code.Log.Write(e.Dispatcher, e.Exception);
            Config.GlobalConfig.ExceptionTime++;
            e.Handled = true;
        }

        private void Plugins_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            Config.ProcesingPluginNameModel.Modified = true;
        }

        private void Template_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            //if (Config.CurrentPlugin == null)
            //{
            //    Config.CurrentPlugin = new PluginsItemCollection();
            //}
            Config.CurrentPlugin.Set(Config.CurrentTemplate.Container.Plugins);
        }

        private void getConfigFromDisk(object sender)
        {
            Config.GlobalConfig.Language = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString();
            try
            {
                Wpf.CommonTools.XML.ConfigContent content = new Wpf.CommonTools.XML.ConfigContent(Config.ConfigPath);
                content.ReadXmlDocument();
                Config.GlobalConfig.AutoOutput = content["AutoOutput"].ToBoolean(Config.GlobalConfig.AutoOutput);
                Config.GlobalConfig.BottomTabIndex = content["BottomTabIndex"].ToInt32();
                Config.GlobalConfig.CheckUpdateInterval = (UpdateIntervalTypes)content["CheckUpdateInterval"].ToInt32(7);
                Config.GlobalConfig.DisabledPlugins = new ObservableCollection<string>(content["DisabledPlugin"].Split(',').Where(p => !string.IsNullOrWhiteSpace(p)));
                Config.GlobalConfig.EnableEscToCloseChildWindows = content["EnableEscToCloseChildWindows"].ToBoolean(Config.GlobalConfig.EnableEscToCloseChildWindows);
                Config.GlobalConfig.IgnoreLog = content["IgnoreLog"].ToBoolean(Config.GlobalConfig.IgnoreLog);
                Config.GlobalConfig.Language = content["Language"];
                Config.GlobalConfig.LastCheckedUpdate = content["LastCheckedUpdate"].ToDateTime(DateTime.Now);
                Config.GlobalConfig.LeftChange = content["LeftChange"].ToDouble(Config.GlobalConfig.LeftChange);
                Config.GlobalConfig.LeftTabIndex = content["LeftTabIndex"].ToInt32(Config.GlobalConfig.LeftTabIndex);
                Config.GlobalConfig.ManagePluginHorizontalChange = content["ManagePluginHorizontalChange"].ToDouble(Config.GlobalConfig.ManagePluginHorizontalChange);
                Config.GlobalConfig.NewTemplateCount = content["NewTemplateCount"].ToInt32();
                Config.GlobalConfig.OutputToClipboard = content["OutputToClipboard"].ToBoolean(Config.GlobalConfig.OutputToClipboard);
                Config.GlobalConfig.PluginType = content["PluginType"].ToInt32(0);
                Config.GlobalConfig.RightTabIndex = content["RightTabIndex"].ToInt32(Config.GlobalConfig.RightTabIndex);
                Config.GlobalConfig.TemplateType = content["TemplateType"].ToInt32(0);
                Config.GlobalConfig.UseWebExplorer = content["UseWebExplorer"].ToBoolean(Config.GlobalConfig.UseWebExplorer);
                Config.GlobalConfig.VerticalChange = content["VerticalChange"].ToDouble(Config.GlobalConfig.VerticalChange);
            }
            catch (Exception ex)
            {
                Convertor.Code.Log.Write(sender, ex);
            }
        }

        private void saveConfigToDisk()
        {
            Wpf.CommonTools.XML.ConfigContent d = new Wpf.CommonTools.XML.ConfigContent(Config.ConfigPath);
            d["AutoOutput"] = Config.GlobalConfig.AutoOutput.ToString();
            d["BottomTabIndex"] = Config.GlobalConfig.BottomTabIndex.ToString();
            d["CheckUpdateInterval"] = Config.GlobalConfig.CheckUpdateInterval.ToInt32().ToString();
            d["DisabledPlugin"] = string.Join(",", Config.GlobalConfig.DisabledPlugins);
            d["EnableEscToCloseChildWindows"] = Config.GlobalConfig.EnableEscToCloseChildWindows.ToString();
            d["IgnoreLog"] = Config.GlobalConfig.IgnoreLog.ToString();
            d["LastCheckedUpdate"] = Config.GlobalConfig.LastCheckedUpdate.ToString();
            d["Language"] = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            d["LeftChange"] = Config.GlobalConfig.LeftChange.ToString();
            d["LeftTabIndex"] = Config.GlobalConfig.LeftTabIndex.ToString();
            d["ManagePluginHorizontalChange"] = Config.GlobalConfig.ManagePluginHorizontalChange.ToString();
            d["NewTemplateCount"] = Config.GlobalConfig.NewTemplateCount.ToString();
            d["OutputToClipboard"] = Config.GlobalConfig.OutputToClipboard.ToString();
            d["PluginType"] = Config.GlobalConfig.PluginType.ToString();
            d["RightTabIndex"] = Config.GlobalConfig.RightTabIndex.ToString();
            d["TemplateType"] = Config.GlobalConfig.TemplateType.ToString();
            d["UseWebExplorer"] = Config.GlobalConfig.UseWebExplorer.ToString();
            d["VerticalChange"] = Config.GlobalConfig.VerticalChange.ToString();
            d.Save();
        }


        private void getStartConfigFromDisk(object sender)
        {
            Config.GlobalConfig.Language = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString();
            try
            {
                Wpf.CommonTools.XML.ConfigContent content = new Wpf.CommonTools.XML.ConfigContent(Config.StartConfigPath);
                content.ReadXmlDocument();
                Config.GlobalConfig.WorkspacePath = content["WorkspacePath"].ToEmpty(null);
                Config.GlobalConfig.WorkspacePathList = new ObservableCollection<string>(content["WorkspacePathList"].Split(',').Where(p => !string.IsNullOrWhiteSpace(p)));
            }
            catch (Exception ex)
            {
                Convertor.Code.Log.Write(sender, ex);
            }
        }

        private void saveStartConfigToDisk()
        {
            Wpf.CommonTools.XML.ConfigContent d = new Wpf.CommonTools.XML.ConfigContent(Config.StartConfigPath);
            d["WorkspacePath"] = Config.GlobalConfig.WorkspacePath;
            d["WorkspacePathList"] = string.Join(",", Config.GlobalConfig.WorkspacePathList);
            d.Save();
        }
    }
}
